<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2017/2/21
 * Time: 13:44
 */

namespace app\admin\controller;

use app\common\model\Apply as ApplyModel;
use app\common\model\Activity;
use app\common\model\Note;

class Apply extends CheckLogin
{

    public function index()
    {
        if ($this->request->isAjax()) {
            $page = (int)$this->request->post('pageIndex');
            $limit = (int)$this->request->post('pageSize');
            $name = $this->request->post('dataName', '');
            $activityId = $this->request->post('dataActivity', '');
            $offset = ($page - 1) * $limit;
            $where = [];
            empty($name) or $where['baby_name'] = ['like', '%' . $name . '%'];
            empty($activityId) or $where['aid'] = ['=', $activityId];
            $applyModel = new ApplyModel();
            $totalCount = $applyModel->where($where)->count();
            $list = $totalCount > 0 ? $applyModel->allApply($where, $offset, $limit) : [];
            if(!empty($list)) {
                foreach($list as $k => $v) {
                    $list[$k]['user_id_format'] = $v->user->nickname;
                    $list[$k]['aid_format'] = $v->activity->title;
                }
            }
            $data = [
                'code' => 0,
                'msg' => 'success',
                'list' => $list,
                'count' => $totalCount
            ];

            return $this->json($data);
        } else {
            $this->assign(['activity' => Activity::all(['status' => 1])]);
            return $this->fetch();
        }
    }

    public function editStatus()
    {
        $id = $this->request->param('apply_id');
        $key = $this->request->post('key');
        $value = $this->request->post('value');

        $apply = ApplyModel::get($id);
        if($apply->save([$key => $value])) {
            // 表示审核未通过
            if($value == 2) {
                $result = Note::sendApplyCheck($apply->mobile);
                if($result['code'] == 0) return $this->jsonSuccess('修改成功, 并发送短信提示');
            }
            return $this->jsonSuccess('修改成功');
        } else {
            return $this->jsonFail('未修改成功');
        }
    }
}
